
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#define THREAD_NUM 2000
static pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;

int sum = 0;



void *sum_func(void *arg)
{
    pthread_mutex_lock(&counter_mutex);
    if(sum <100)
    {

        sum++;  
    }
    pthread_mutex_unlock(&counter_mutex);
}

int main(int argc, char const *argv[])
{
    //  利用多线程进行累加操作
    pthread_t threads[THREAD_NUM];

    for (size_t i = 0; i < THREAD_NUM; i++)
    {
         pthread_create(&threads[i], NULL, sum_func, NULL);
    }
    
    sleep(2);
    printf("sum = %d\n", sum);
    pthread_mutex_destroy(&counter_mutex);

    return 0;
}
